﻿using B.S.Basic.ErrorCode;
using B.S.Basic.Infratrucate;
using B.S.Basic.Write.API.Application;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations.Operations;

namespace B.S.Basic.Write.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ManagementController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ManagementController> logger;
        private readonly DataDBContext db;
 
        public ManagementController(IMediator mediator, ILogger<ManagementController> logger, DataDBContext db)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.db = db;
        }
        [HttpPost]
        public async Task<APIResult<object>> AddUser(AddCommand add)
        {
            try
            {
                logger.LogInformation("调用添加方法");
                return await mediator.Send(add);
            }
            catch (Exception ex)
            {
                logger.LogError("添加方法出错" + ex.Message);
                throw;
            }
            
        }
        [HttpPost]
        public async Task<APIResult<object>> AddMy(AddMyCommand add)
        {
            
            try
            {
                logger.LogInformation("调用添加方法");
                return await mediator.Send(add);
            }
            catch (Exception ex)
            {
                logger.LogError("添加方法出错" + ex.Message);
                throw;
            }
        }
        [HttpGet]
        public async Task<IActionResult> ExportData()
        {
            var dataItems = await db.DataItems.ToListAsync();
            var csvContent = "Id,Name,Description\n";
            foreach (var item in dataItems)
            {
                csvContent += $"{item.Id},{item.Name},{item.Description}\n";
            }
            var bytes = System.Text.Encoding.UTF8.GetBytes(csvContent);
            return File(bytes, "text/csv", "exported_data.csv");
        }
    }
}
